package com.mingqijia.gassafety.console.migrate.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONObject;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.console.migrate.config.CoordinateTransformer;
import com.mingqijia.gassafety.console.migrate.config.MigrateConfig;
import com.mingqijia.gassafety.console.migrate.handler.MigrateInsertHandler;
import com.mingqijia.gassafety.console.migrate.model.MigrateCompanyModel;
import com.mingqijia.gassafety.console.migrate.service.MigrateService;
import com.mingqijia.gassafety.db.entity.ConsumerSubsCode;
import com.mingqijia.gassafety.db.entity.MigrateConsumer;
import com.mingqijia.gassafety.db.entity.MigrateContacts;
import com.mingqijia.gassafety.db.entity.MigrateDtu;
import com.mingqijia.gassafety.db.mapper.ConsumerSubsCodeMapper;
import com.mingqijia.gassafety.db.mapper.MigrateConsumerMapper;
import com.mingqijia.gassafety.db.mapper.MigrateContactsMapper;
import com.mingqijia.gassafety.db.mapper.MigrateDtuMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 数据迁移
 * @Author: zero
 * @CreateTime: 2022-11-30
 */
@Service
@Slf4j
public class MigrateServiceImpl implements MigrateService {

    @Resource
    private MigrateConsumerMapper migrateConsumerMapper;
    @Resource
    private MigrateContactsMapper migrateContactsMapper;
    @Resource
    private MigrateDtuMapper migrateDtuMapper;

    @Resource
    private MigrateInsertHandler migrateInsertHandler;

    //请求次数控制（有且仅有一次）
    private volatile Boolean requestFlag = false;

    //请求次数控制（有且仅有一次）
    private volatile Boolean requestIdFlag = false;

    @Resource
    private ConsumerSubsCodeMapper consumerSubsCodeMapper;

    @Override
    public List<Integer> migrateData() throws Exception {
        if (requestFlag) {
            log.warn("重复请求");
            return new ArrayList<>();
        }
        List<MigrateConsumer> consumers = migrateConsumerMapper.selectList();
        if (CollectionUtil.isEmpty(consumers)) {
            return new ArrayList<>();
        }
        List<ConsumerSubsCode> list = consumerSubsCodeMapper.getList();
        Map<String, String> subsCodeMap = list.stream().collect(Collectors.toMap(ConsumerSubsCode::getConsumerId, ConsumerSubsCode::getSubsCode));
        List<MigrateContacts> contacts = migrateContactsMapper.selectList();
        Map<Integer, List<MigrateContacts>> contactsMap = contacts.stream().collect(Collectors.groupingBy(MigrateContacts::getConsumerId));

        List<MigrateDtu> dtus = migrateDtuMapper.selectList();
        Map<Integer, List<MigrateDtu>> dtusMap = dtus.stream().collect(Collectors.groupingBy(MigrateDtu::getConsumerId));

        Map<String, MigrateCompanyModel> companyModelMap = MigrateConfig.companyModelMap;
        List<Integer> failConsumerList = new ArrayList<>();
        for (MigrateConsumer consumer : consumers) {
            //consumer 组装
            MigrateCompanyModel migrateCompanyModel = companyModelMap.get(consumer.getSpId());
            consumer.setSpId(migrateCompanyModel.getSpId());
            consumer.setPath(migrateCompanyModel.getPath());
            consumer.setCustName(consumer.getName());
            consumer.setDepartmentId(migrateCompanyModel.getDepartmentId());
            consumer.setTemplateType(1);
            consumer.setCustAddress(consumer.getAddress());
            consumer.setSubsCode(subsCodeMap.get(String.valueOf(consumer.getId())));
            //坐标转换
            if (consumer.getPositionLon() != null || consumer.getPositionLat() != null) {
                double[] doubles = CoordinateTransformer.transformBD09ToGCJ02(consumer.getPositionLon()
                        , consumer.getPositionLat());
                consumer.setPositionLon(doubles[0]);
                consumer.setPositionLat(doubles[1]);
            }
            //字典直接迁移
//            consumer.setIndustryType();

            //Contacts组装
            List<MigrateContacts> contactsList = contactsMap.get(consumer.getId());

            if (!CollectionUtil.isEmpty(contactsList)) {
                consumer.setCustPhone(contactsList.get(0).getTelephone());
            }
            //dtu 组装
            List<MigrateDtu> dtuList = dtusMap.get(consumer.getId());
            Boolean flag = migrateInsertHandler.insertDB(consumer, contactsList, dtuList);
            if (!flag) {
                failConsumerList.add(consumer.getId());
            }
            requestFlag = true;
        }
        log.error("迁移失败的consumerList: {}", JSONObject.toJSON(failConsumerList));
        return failConsumerList;
    }


//    @Override
//    public List<Integer> migrateDataByIdList(List<Integer> idList) throws Exception {
//        if (CollectionUtil.isEmpty(idList)) {
//            return new ArrayList<>();
//        }
//        if(requestIdFlag){
//            log.warn("重复请求");
//            return new ArrayList<>();
//        }
//        List<MigrateConsumer> consumers = migrateConsumerMapper.selectListByIdList(idList);
//
//        if (CollectionUtil.isEmpty(consumers)) {
//            return new ArrayList<>();
//        }
//        List<MigrateContacts> contacts = migrateContactsMapper.selectList();
//
//        Map<Integer, List<MigrateContacts>> contactsMap = contacts.stream().collect(Collectors.groupingBy(MigrateContacts::getConsumerId));
//
//        List<MigrateDtu> dtus = migrateDtuMapper.selectList();
//        Map<Integer, List<MigrateDtu>> dtusMap = dtus.stream().collect(Collectors.groupingBy(MigrateDtu::getConsumerId));
//
//        Map<String, MigrateCompanyModel> companyModelMap = MigrateConfig.companyModelMap;
//        List<Integer> failConsumerList = new ArrayList<>();
//        for (MigrateConsumer consumer : consumers) {
//            //consumer 组装
//            MigrateCompanyModel migrateCompanyModel = companyModelMap.get(consumer.getSpId());
//            consumer.setSpId(migrateCompanyModel.getSpId());
//            consumer.setPath(migrateCompanyModel.getPath());
//            consumer.setDepartmentId(migrateCompanyModel.getDepartmentId());
//            consumer.setTemplateType(1);
//            //字典直接迁移
////            consumer.setIndustryType();
//
//            //Contacts组装
//            List<MigrateContacts> contactsList = contactsMap.get(consumer.getId());
//            //dtu 组装
//            List<MigrateDtu> dtuList = dtusMap.get(consumer.getId());
//            Boolean flag = migrateInsertHandler.insertDB(consumer, contactsList, dtuList);
//            if (!flag) {
//                failConsumerList.add(consumer.getId());
//            }
//            requestIdFlag = true;
//        }
//        log.error("迁移失败的consumerList: {}", JSONObject.toJSON(failConsumerList));
//        return failConsumerList;
//    }

    @Override
    public void unBoundDtu() {
        List<MigrateDtu> dtuList = migrateDtuMapper.selectUnBoundDtuList();
        Map<String, MigrateCompanyModel> companyModelMap = MigrateConfig.companyModelMap;
        Boolean flag = migrateInsertHandler.insertDTUDB(dtuList, companyModelMap);
        if (!flag) {
            log.error("迁移失败的dtuList: {}", dtuList);
        }
    }

    @Override
    public void importData(MultipartFile file) {
        List<Integer> errors = new ArrayList<>();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new BizException("获取文件流失败");
        }
        ExcelReader reader = ExcelUtil.getReader(inputStream, 0); //指定输入流和sheet
        List<List<Object>> read = reader.read(1, reader.getRowCount());
        Map<String,String> map = new HashMap<>();
        List<ConsumerSubsCode> list = new ArrayList<>();
        for (int i = 0; i < read.size(); i++) {
            List<Object> objects = read.get(i);
            ConsumerSubsCode consumerSubsCode = new ConsumerSubsCode();
            consumerSubsCode.setConsumerId(String.valueOf(objects.get(0)));
            consumerSubsCode.setSubsCode(String.valueOf(objects.get(1)).replace("↵",""));
            if(map.get(consumerSubsCode.getConsumerId())!=null){
                //存在 跳过（默认取第一个）
               continue;
            }
            list.add(consumerSubsCode);
            map.put(consumerSubsCode.getConsumerId(),consumerSubsCode.getSubsCode());
        }
        consumerSubsCodeMapper.insertMigrateBatch(list);

    }


}
